package com.cnswhy.cloud.server.core.base;

import com.cnswhy.cloud.common.core.exception.BizException;
import com.cnswhy.cloud.common.core.mybatis.conditions.Wraps;
import com.cnswhy.cloud.common.redis.service.RedisService;
import com.cnswhy.cloud.server.core.entity.BaseBank;
import com.cnswhy.cloud.server.core.entity.BaseBankBin;
import com.cnswhy.cloud.server.core.service.base.BaseBankBinService;
import com.cnswhy.cloud.server.core.service.base.BaseBankService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class BankService {
    @Autowired
    RedisService redisService;
    @Autowired
    BaseBankBinService baseBankBinService;
    @Autowired
    BaseBankService baseBankService;

    public BaseBankBin getBankBin(String bin, int length) throws BizException {
        if(StringUtils.isEmpty(bin)){
            throw new BizException("bin不可为空");
        }
        BaseBankBin bankBin = (BaseBankBin) redisService.get("BaseBankBin" + bin + length);
        if(bankBin != null){
            return bankBin;
        }
        bankBin =baseBankBinService.getOne(Wraps.<BaseBankBin>lbQ().eq(BaseBankBin::getBankBin,bin).eq(BaseBankBin::getCardLength,length));
        if(bankBin == null){
            throw new BizException("卡BIN未找到，请确认卡号是否正确");
        }
        redisService.set("BaseBankBin" + bin + length, bankBin);
        return bankBin;
    }
    public BaseBankBin getBankBinByCardId(String cardId) throws BizException {
        if(StringUtils.isEmpty(cardId)){
            throw new BizException("card_id is null");
        }
        if(cardId.length()<= 10){
            throw new BizException("card_id length < 10");
        }
        BaseBankBin bankBin = null;
        int pfdLength = 10;
        do{
            bankBin = baseBankBinService.getOne(Wraps.<BaseBankBin>lbQ()
                    .eq(BaseBankBin::getBankBin,cardId.substring(0,pfdLength))
                    .eq(BaseBankBin::getLength,pfdLength)
                    .eq(BaseBankBin::getCardLength,cardId.length()));
            if(bankBin != null){
                return bankBin;
            }
            pfdLength --;
        }while(pfdLength > 1);
        if(bankBin == null){
            throw new BizException("卡BIN未找到，请确认卡号是否正确");
        }
        return bankBin;
    }
    public BaseBank getBank(String abbr) throws BizException {
        if(StringUtils.isEmpty(abbr)){
            throw new BizException("银行简称不可为空");
        }
        BaseBank bank = (BaseBank) redisService.get("BaseBank" + abbr);
        if(bank != null){
            return bank;
        }
        bank =baseBankService.getOne(Wraps.<BaseBank>lbQ().eq(BaseBank::getAbbr,abbr));
        if(bank == null){
            throw new BizException("银行未找到");
        }
        redisService.set("BaseBank" + abbr, bank);
        return bank;
    }
}
